export function debouce(fn, delay) {
  let timer = null
  return function () {
    const arg = arguments
    return new Promise((resolve) => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        resolve(fn.apply(this, arg))
      }, delay)
    })
  }
}

export function takeLatest(fn) {
  let lastRun = null
  return async function () {
    const arg = arguments
    const currentRun = Date.now()
    lastRun = currentRun
    const res = await fn.apply(this, arg)
    if (lastRun === currentRun) return res
    console.log(res)
    console.log('takeLatest drop')
    throw new Error('takeLatest drop')
  }
}

/**
 * 事件格式化
 * @param {*} date
 */
export function fmtDate(date) {
  const year = date.getFullYear()
  const month = change(date.getMonth() + 1)
  const day = change(date.getDate())
  function change(t) {
    if (t < 10) {
      return `0${t}`
    }
    return t
  }
  return `${year}-${month}-${day}`
}

/**
 * 过滤obj val为undeined的key
 * @param {*} obj
 */
export function filterObject(obj) {
  const ret = {}
  Object.keys(obj)
    .filter((key) => obj[key] !== undefined)
    .forEach((key) => (ret[key] = obj[key]))
  return ret
}
